using Light.Assets.Scripts.EventManager;
using UnityEngine;

namespace Light
{
    public class DamageReceiver : CoreComponent, IDamageable
    {
        [SerializeField] private GameObject damageParticles; //����ʱ����������
        [SerializeField] private AudioClip[] damageSounds; //����ʱ����Ч

        public float attackInterval = 1f; // ���ˣ���λ��  
        [SerializeField] private CoreComp<AudioCom> audioManager;

        private HeallthPanelController healthController; //ͬ��Ѫ��UI
        private float lastAttackTime; // ��һ�����˵�ʱ��
        [SerializeField] private CoreComp<ParticleManager> particleManager;

        [SerializeField] private CoreComp<Stats> stats;

        protected override void Awake()
        {
            base.Awake();

            healthController = core.transform.parent.Find("CanvasCamera").gameObject
                .GetComponentInChildren<HeallthPanelController>();
            stats = new CoreComp<Stats>(core);
            particleManager = new CoreComp<ParticleManager>(core);
            audioManager = new CoreComp<AudioCom>(core);
        }

        public void Damage(float damage, Transform transform)
        {
            if (Time.time - lastAttackTime < attackInterval && core.transform.parent.gameObject.name == "Player")
                return;
            lastAttackTime = Time.time;
            TurnOver(transform);
            stats.Comp?.Health.Decrease(damage);
            particleManager.Comp?.StartParticleWithRandowRotation(damageParticles);
            audioManager.Comp?.PlayRandomSFX(damageSounds);
            healthController.Refresh(stats.Comp.Health.CurrentValue);
            if (stats.Comp?.Health.CurrentValue <= 0)
                Death();
        }

        public void TurnOver(Transform transform)
        {
            if ((core.transform.parent.transform.position.x - transform.position.x > 0f &&
                 core.transform.parent.transform.rotation.y >= 0f)
                || (core.transform.parent.transform.position.x - transform.position.x < 0f &&
                    core.transform.parent.transform.rotation.y < 0f))
                core.Movement.FilpImmediately();
        }

        public void Death()
        {
            var evt = DeathEvent.Get();
            evt.transform = core.transform;
            EventManager.SendEvent(evt);
        }
    }
}